package de.g18.scavengerhunt.service;

import com.google.android.maps.GeoPoint;

import de.g18.scavengerhunt.AppApplicationContext;
import de.g18.scavengerhunt.AppConstants;
import de.g18.scavengerhunt.utils.WebserviceUtil;

/**
 * This threads sends the devices location to the webservice
 */
public class SendPositionThread implements Runnable {

    private boolean        running        = false;

    private int            userId         = 0;

    private WebserviceUtil webserviceUtil = null;

    public SendPositionThread(int userId) {
        this.userId = userId;
        webserviceUtil = WebserviceUtil.getInstance();
    }

    @Override
    public void run() {
        running = true;
        GeoPoint geoPointToPull = null;
        while (running) {
            geoPointToPull = GeoDataGateway.getCurrentPositionGeoPoint();
            if (geoPointToPull != null) {
                if (AppApplicationContext.getUser() != null) {
                    AppApplicationContext.getUser().setCurrentGeoPoint(geoPointToPull);
                }
                webserviceUtil.sendOwnPosition(userId, geoPointToPull.getLatitudeE6(), geoPointToPull.getLongitudeE6());
            }
            try {
                Thread.sleep(AppConstants.POSITION_SEND_THREAD_SLEEP_TIME_IN_MS);
            } catch (InterruptedException e) {
                // ignore
            }
        }
    }

   
    /**
     * Stopps this thread
     */
    public void stop() {
        running = false;
    }
}